import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import User from '../components/user/User.vue'
import ItemCat from '../components/items/ItemCat.vue'
import Item from '../components/items/Item.vue'
import addItem from '../components/items/addItem.vue'
import order from '../components/items/order'

Vue.use(VueRouter)// 声明绑定使用路由
const routes = [
  { path: '/', redirect: '/login' }, // 当访问根路径时，重定向到 /login路径
  { path: '/login', component: Login }, // 当访问/login时，将Login组件内容在App.vue预留
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [// 当访问/home时，将Home组件内容在App.vue预留的占位符位置显示
      { path: '/welcome', component: Welcome }, // 当访问/welcome时，将Welcome组件内容在Home.vue预留的占位符位置显示
      { path: '/user', component: User },
      { path: '/itemCat', component: ItemCat },
      { path: '/item', component: Item },
      { path: '/item/addItem', component: addItem },
      { path: '/order', component: order }
    ]
  }
]
// 定义路由对象
const router = new VueRouter({
  routes
})
/*
beforeEach:循环遍历用户的所有请求(拦截)
  在其中需要定义一个回调函数，声明具体的拦截策略
回调函数中有三个参数
  to：要访问的请求路径
  from：从哪个页面来的
  next：表示请求放行
*/
router.beforeEach((to, from, next) => {
  // console.log(to);
  // console.log(from);
  if (to.path === '/login') { // 如果你去的是登录页面，放行
    next()
    return
  }
  const token = window.sessionStorage.getItem('token')
  console.log(token)
  if (!token) { // 如果没登录，去登录
    next('/login')
  } else {
    // next表示放行
    next()
  }
})

export default router
